#include "common.h"

int minFallingPathSum(vector<vector<int>>& matrix)
{
	int n = matrix.size();
	int m = matrix[0].size();
	vector<vector<int>> dp(n + 1, vector<int>(m + 2, INT_MAX));
	for (int i = 0; i < m + 2; i++)
	{
		dp[0][i] = 0;
	}
	for (int i = 1; i < n + 1; i++)
	{
		for (int j = 1; j < m + 1; j++)
		{
			dp[i][j] = min(dp[i - 1][j], min(dp[i - 1][j - 1], dp[i - 1][j + 1])) + matrix[i - 1][j - 1];
		}
	}
	int ans = INT_MAX;
	for (int j = 1; j < m + 1; j++)
	{
		ans = min(ans, dp[n][j]);
	}
	return ans;
}
